package com.jlee.android.pimclient.tests;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.Contacts;
import android.test.ServiceTestCase;

import com.jlee.android.pimclient.service.ContactRecorder;
import com.jlee.android.pimclient.service.PIMClientService;

public class ContactTest extends ServiceTestCase<PIMClientService> {
	private MockContactRecorder mContactRecorder;
	private PIMClientService mService;
	private ContentResolver mResolver;

	public ContactTest() {
		super(PIMClientService.class);
		
		setupService();
	}
	
	@Override
	public void setUp() {
		mContactRecorder = new MockContactRecorder();
		
		mService = getService();
		assertNotNull(mService);
		assertNotNull(mService.mContentObserver);
		
		mService.mContentObserver.setContactRecorder(mContactRecorder);
	}
	
	@Override
	public void tearDown() {
		mContactRecorder.clearData();
	}
	
	public void testAddContactName() throws InterruptedException {
		final String name = "New Contact Name";
		
		// assert initial status
		assertFalse(mContactRecorder.hasName(name));

		// Construct the data to be inserted
		addContact(name);

		Thread.sleep(3000);
		assertTrue(mContactRecorder.hasName(name));
	}
	
	private void addContact(String name) {
		ContentValues values = new ContentValues();
		values.put(Contacts.People.NAME, name);
		
		Uri uri = mResolver.insert(Contacts.People.CONTENT_URI, values);
		assertNotNull(uri);
	}

	private class MockContactRecorder implements ContactRecorder {
		ArrayList<String> mNameList;

		public void recordName(String name) {
			mNameList.add(name);
		}
		
		public void clearData() {
			for (String name : mNameList) {
				String where = Contacts.People.NAME + "=?";
				String[] selection = {name};

				mResolver.delete(Contacts.People.CONTENT_URI, where, selection);
			}

			mNameList.clear();
		}
		
		public boolean hasName(String name) {
			for (String n : mNameList) {
				if (n.equals(name)) {
					return true;
				}
			}
			
			return false;
		}
	}
}
